
public class OneWayLinkedList<E> implements IList<E> {


	private Node head = null;
	private int size = 0;

	public OneWayLinkedList() {
		head = null;
		size = 0;
	}

	@Override
	public void add(E element) {
		size++;
		head = new Node(element, head);
	}

	@Override
	public void remove(E element) {
		if ( head == null ) {
			throw new IllegalArgumentException("The List is empty");
		} else if ( head.element.equals(element) ) {
			size--;
			head = head.next;
		} else {
			for ( Node node = head; node.next != null; node = node.next ) {
				if ( node.next.element.equals(element) ) {
					node.next = node.next.next;
					size--;
					break;
				}
			}
		}
	}

	@Override
	public boolean contains(E element) {
		for ( Node node = head; node != null; node = node.next ) {
			if ( node.element.equals(element) ) {
				return true;
			}
		}
		return false;
	}

	@Override
	public int size() {
		return size;
	}

	@Override
	public void clear() {
		head = null;
		size = 0;
	}

	@Override
	public IIterator iterator() {
		return new OneWayLinkedListIterator();
	}


	//Elements of List
	private class Node<E> {
		E element;
		Node next;

		Node(E element, Node next) {
			this.element = element;
			this.next = next;
		}
	}


	private class OneWayLinkedListIterator<E> implements IIterator<E>{
		private Node top = head;
		private Node prevRef = head;

		@Override
		public E next() {
			E element = (E) top.element;
			prevRef = top;
			top = top.next;

			return element;
		}

		@Override
		public boolean hasNext() {
			return top != null;
		}

		@Override
		public void remove() {
			prevRef.next = prevRef.next.next;
			size--;
		}

	}

	@Override
	public String toString() {
		String result = "";
		for ( Node node = head; node != null; node = node.next ) {
			result += node.element.toString();
		}
		return result;
	}
}



